import requests,threading
from lxml import etree
import sys,os
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout,QHBoxLayout, QLabel, QMenu, QAction 
from PyQt5.QtCore import Qt,QPoint,QRect
from PyQt5.QtGui import QPainter, QColor


from PIL import ImageGrab

# 获取整个屏幕的截图
screenshot = ImageGrab.grab()

# 获取屏幕的宽度和高度
screen_width, screen_height = screenshot.size

print("Screen Width:", screen_width)
print("Screen Height:", screen_height)

# 可以通过像素坐标获取像素信息
pixel_color = screenshot.getpixel((100, 100))
print("Pixel color at (100, 100):", pixel_color)


class BlogData:
    # 类变量
    # 文章总数、粉丝数、点赞数、收藏数、访问量、最大访问量以及每一篇博客的标题、访问量、链接
    total_number = 0     
    article_number = 0 
    fans_number = 0 
    thumbs_up_number = 0 
    collection_number = 0 
    cc4 = 0
    cc2 = 0
    
    article_title_output = []
    article_url_output = []
    article_visit_number_output = []

    def __init__(self):
        # 实例变量
        pass

    def loadBase(self,blogName):    #获取基础数据
        head = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36'}
        html = requests.get('https://blog.csdn.net/{}/article/list/{}'.format(blogName,0),headers = head)
        etree_html = etree.HTML(html.text)
        # visit_number = etree_html.xpath('//*[@id="asideProfile"]/div[2]/dl[4]/dt/span/text()')[0]
        self.article_number = etree_html.xpath('//*[@id="asideProfile"]/div[2]/dl[1]/a/dt/span/text()')[0]
        self.cc2 = etree_html.xpath('//*[@id="asideProfile"]/div[2]/dl[2]/a/dt/span/text()')[0]
        self.fans_number = etree_html.xpath('//*[@id="fan"]/text()')[0]
        self.thumbs_up_number = etree_html.xpath('//*[@id="asideProfile"]/div[4]/dl[3]/dt/span/text()')[0]
        self.collection_number = etree_html.xpath('//*[@id="asideProfile"]/div[4]/dl[5]/dt/span/text()')[0]

    def loadTotal(self,blogName):       # 获取全部数据
        page = 0
        while True:
            page = page + 1
            head = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36'}
            html = requests.get('https://blog.csdn.net/{}/article/list/{}'.format(blogName,page),headers = head)
            etree_html = etree.HTML(html.text)
            # visit_number = etree_html.xpath('//*[@id="asideProfile"]/div[2]/dl[4]/dt/span/text()')[0]
            self.article_number = etree_html.xpath('//*[@id="asideProfile"]/div[2]/dl[1]/a/dt/span/text()')[0]
            self.fans_number = etree_html.xpath('//*[@id="fan"]/text()')[0]
            self.thumbs_up_number = etree_html.xpath('//*[@id="asideProfile"]/div[4]/dl[3]/dt/span/text()')[0]
            self.collection_number = etree_html.xpath('//*[@id="asideProfile"]/div[4]/dl[5]/dt/span/text()')[0]
            article_title = etree_html.xpath('//*[@id="articleMeList-blog"]/div[2]/div/h4/a/text()', encoding='utf-8')

            for i in article_title:
                title = str(i).replace('\n', '').replace(' ', '')
                if title != '':
                    self.article_title_output.append(title)

            article_visit_number = etree_html.xpath('//*[@id="articleMeList-blog"]/div[2]/div/div[1]/p/span[2]/text()')

            for number in article_visit_number:
                self.article_visit_number_output.append(int(number))
                self.total_number += int(number)

            article_urls = etree_html.xpath('//*[@id="articleMeList-blog"]/div[2]/div/h4/a/@href')
            for article_url in article_urls:
                self.article_url_output.append(str(article_url))

            if len(article_visit_number) == 0:
                break


class CustomWidget(QWidget):

    def __init__(self):
        super().__init__()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.dragging = False
        self.loading = False
        self.magnetic_distance = 20  # 定义磁吸的距离

        # self.setMinimumSize(200, 150)
        self.setFixedSize(150, 150)

        self.total_label = QLabel("文章总数：")
        self.follower_label = QLabel("粉丝数：")
        self.likes_label = QLabel("点赞数：")
        self.favorites_label = QLabel("收藏数：")

        self.total_label2 = QLabel("--")
        self.follower_label2 = QLabel("--")
        self.likes_label2 = QLabel("--")
        self.favorites_label2 = QLabel("--")


        hLayout = QHBoxLayout()
        hLayout.setContentsMargins(15,15,15,15)

        layout = QVBoxLayout()
        layout.setContentsMargins(0,0,0,0)
        layout.addWidget(self.total_label)
        layout.addWidget(self.follower_label)
        layout.addWidget(self.likes_label)
        layout.addWidget(self.favorites_label)
        hLayout.addLayout(layout)

        layout2 = QVBoxLayout()
        layout2.setContentsMargins(0,0,0,0)
        layout2.addWidget(self.total_label2)
        layout2.addWidget(self.follower_label2)
        layout2.addWidget(self.likes_label2)
        layout2.addWidget(self.favorites_label2)
        hLayout.addLayout(layout2)

        self.total_label2.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.follower_label2.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.likes_label2.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.favorites_label2.setAlignment(Qt.AlignmentFlag.AlignRight)

        self.setLayout(hLayout)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        color = QColor(QColor("#ecf0f1"))
        color.setAlphaF(0.8)
        painter.setBrush(color)
        painter.setPen(Qt.NoPen)
        painter.drawRoundedRect(self.rect(), 6, 6)
        if self.loading :
            painter.setBrush(QColor("#2ed573"))
            painter.drawEllipse(QRect(6,6,12,12))

    def contextMenuEvent(self, event):
        menu = QMenu(self)
        # menu.setStyleSheet("QMenu::item { height: 30px; }")  # 设置菜单项高度为40像素
        close_action = QAction("关闭", self)
        close_action.triggered.connect(self.close)
        menu.addAction(close_action)
        menu.exec_(event.globalPos())

    def open_settings(self):
        config_file = os.path.join(os.path.dirname(__file__), "config.json")
        if os.path.exists(config_file):
            os.system("open " + config_file)  # 在Linux系统中使用xdg-open打开文件
        
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = True
            self.offset = event.globalPos() - self.pos()
    def mouseMoveEvent(self, event):
        if self.dragging:
            pos = event.globalPos() - self.offset
            # if pos.y() <= 20 :
            #     pos.setY(0)
            self.move(pos)
            self.snap_to_edge()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = False

    def snap_to_edge(self):
        desktop = QApplication.desktop()
        screen_rect = desktop.availableGeometry()
        window_rect = self.geometry()

        if window_rect.left() <= screen_rect.left() + self.magnetic_distance:
            self.move(screen_rect.left(), self.y())
        elif window_rect.right() >= screen_rect.right() - self.magnetic_distance:
            self.move(screen_rect.right() - window_rect.width(), self.y())

        if window_rect.top() <= screen_rect.top() + self.magnetic_distance:
            self.move(self.x(), screen_rect.top())
        elif window_rect.bottom() >= screen_rect.bottom() - self.magnetic_distance:
            self.move(self.x(), screen_rect.bottom() - window_rect.height())

    def updateBlogData(self, count,fans,likes,favorites):
        self.total_label2.setText(str(count))
        self.follower_label2.setText(str(fans))
        self.likes_label2.setText(str(likes))
        self.favorites_label2.setText(str(favorites))
    
    def setLoading(self,flag) :
        self.loading = flag
        self.update()

blog = BlogData()

app = QApplication(sys.argv)
widget = CustomWidget()
widget.show()

def updateUi():
    widget.setLoading(True)
    print("updateUi data......")
    blog.loadBase("weixin_42887343")
    widget.updateBlogData(blog.article_number,blog.fans_number,blog.thumbs_up_number,blog.collection_number)
    widget.setLoading(False)

def onExit():   # 定义退出处理函数
    timer.cancel()

if __name__ == '__main__':
    # app.aboutToQuit.connect(onExit) # 注册退出处理函数
    updateUi()
    timer = threading.Timer(10, updateUi)
    timer.start()
    sys.exit(app.exec_())


# print('article_number', blog.article_number)     #文章总数
# print('fans_number', blog.fans_number)       #粉丝数
# print('thumbs_up_number', blog.thumbs_up_number)     #点赞数
# print('collection_number', blog.collection_number)       #收藏数
# print('total_visit_number', blog.total_number)       #访问量
# print('max_article_visit_number', max(blog.article_visit_number_output))     #最大访问量
# for i in range(len(blog.article_visit_number_output)):
#     print(blog.article_title_output[i], '\t', blog.article_visit_number_output[i], '\t',blog.article_url_output[i])

